package com.jf.car.controller;

import com.alibaba.fastjson.JSON;
import com.jf.car.bean.Car;
import com.jf.car.service.CarService;
import com.jf.car.service.CategoryService;
import com.jf.car.service.impl.CarServiceImpl;
import com.jf.car.service.impl.CategoryServiceImpl;
import com.jf.car.util.MyUtils;
import com.jf.car.util.PageInfo;
import com.jf.car.util.ResultJson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/car")
public class CarServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String param = request.getParameter("param");
        CarService carService = new CarServiceImpl();
        CategoryService categoryService = new CategoryServiceImpl();
        Car car = new Car();
        car.setId(MyUtils.string2Int(request.getParameter("id")));
        car.setCarNo(request.getParameter("carNo"));
        car.setColor(request.getParameter("color"));
        car.setCategoryId(MyUtils.string2Int(request.getParameter("categoryId")));
        car.setStatus(MyUtils.string2Int(request.getParameter("status")));
        car.setImgs(MyUtils.string2Array(request.getParameter("imgs")));

        if(MyUtils.isStringEmpty(param)){
            request.setAttribute("categoryList",categoryService.getAll());
            request.getRequestDispatcher("/WEB-INF/pages/admin/car/car-list.jsp").forward(request,response);
        }
        if("edit".equals(param)){
            request.getRequestDispatcher("/WEB-INF/pages/admin/car/car-edit.jsp").forward(request,response);
        }
        if("list".equals(param)){
            int page = MyUtils.string2Int(request.getParameter("page"),1);
            int limit = MyUtils.string2Int(request.getParameter("limit"),5);
            PageInfo pageInfo = new PageInfo(page,limit);
            response.getWriter().println(JSON.toJSON(carService.getPage(pageInfo,car)));
        }
        if("info".equals(param)){
            response.getWriter().println(JSON.toJSON(carService.info(car.getId())));
        }
        if("update".equals(param)){
            response.getWriter().println(JSON.toJSON(carService.saveOrUpdate(car)));
        }
        if("delete".equals(param)){
            response.getWriter().println(carService.delete(car.getId()));
        }
    }
}
